package com.cuz.daileetcode.bat100;

public class 公式字符串计算结果 {

    static boolean isNumber(String str) {//判断表达式是不是只有一个数字
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '.') {
                return false;
            }
        }
        return true;
    }

    static double calculateExpress(String express) {
        //base case
        //空串 or 单独一个数字 那么序列化返回
        if (express.isEmpty() || isNumber(express)) {
            return express.isEmpty() ? 0 : Double.parseDouble(express);
        }
        //优先级1 计算括号的内容
        if (express.contains(")")) {
            //最后一个左括号
            int lIndex = express.lastIndexOf("(");
            //对应的右括号
            int rIndex = express.indexOf(")", lIndex);
            double bracketContentRes = calculateExpress(express.substring(lIndex + 1, rIndex));
            String beforeBracket = express.substring(0, lIndex);
            String afterBracket = express.substring(rIndex + 1);
            return calculateExpress(beforeBracket + bracketContentRes + afterBracket);
        }
        if (express.contains("+")) {
            int index = express.lastIndexOf("+");
            double beforeAdd = calculateExpress(express.substring(0, index));
            double addCalRes = calculateExpress(express.substring(index + 1));
            return beforeAdd + addCalRes;
        }
        if (express.contains("-")) {
            int index = express.lastIndexOf("-");
            double beforeReduce = calculateExpress(express.substring(0, index));
            double afterReduce = calculateExpress(express.substring(index + 1));
            return beforeReduce - afterReduce;
        }
        if (express.contains("*")) {
            int index = express.lastIndexOf("*");
            double beforeMulti = calculateExpress(express.substring(0, index));
            double afterMulti = calculateExpress(express.substring(index + 1));
            return beforeMulti * afterMulti;
        }
        if (express.contains("/")) {
            int index = express.lastIndexOf("/");
            double beforeDiv = calculateExpress(express.substring(0, index));
            double afterDiv = calculateExpress(express.substring(index + 1));
            return beforeDiv / afterDiv;
        }
        throw new IllegalArgumentException("非法表达式:" + express);
    }

}

